package cerebrum.controller.wallpaper;

import cerebrum.enums.SetUpMeaages;

import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

public class LogUtils {
    public static int getMax(int[] array) {
        Arrays.sort(array);
        return array[array.length - 1];
    }

    /**
     * @param state   日志状态分类
     * @param message 日志详情
     */
    public static void saveLog(int state, String message, String url) {
        String logpath = SetUpMeaages.LOG_PATH.getPath();

        long num = 0;

        LocalDate name = LocalDate.now();
        File saveDir = null;
        if (state == 1) {
            saveDir = new File(logpath);
        } else if (state == 0) {
            saveDir = new File(logpath + "\\errors");
        } else if (state == 3) {
            saveDir = new File(logpath + "\\update");
        }
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }
        File file = new File(saveDir + "\\" + name + ".txt");
        if (file.exists()) {
            try {
                num = getLineNumber(file);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            num++;
        }

        try (FileOutputStream out = new FileOutputStream(file, true);) {

            LocalDateTime time = LocalDateTime.now();
            String format = time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String log = num + ".  时间: " + format + ",从[" + url + "]" + message;
            out.write(log.getBytes());
            //换行
            String newLine = System.getProperty("line.separator");
            out.write(newLine.getBytes());
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    private static long getLineNumber(File file) throws IOException {
        if (file.exists()) {
            try (FileReader fileReader = new FileReader(file);
                    LineNumberReader lineNumberReader = new LineNumberReader(fileReader);) {
                lineNumberReader.skip(Long.MAX_VALUE);
                long lines = lineNumberReader.getLineNumber() + 1;
                return lines;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }
}
